<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <!-- 表单 -->
      <el-form
        :model="goodsForm"
        :rules="rules"
        ref="goodsForm"
        label-width="100px"
        class="demo-goodsForm"
      >
        <el-form-item label="类目选择" prop="category">
          <el-button size="mini" type="primary" @click="innerVisible = true"
            >类目选择</el-button
          >
          <el-tag
            style="margin-left: 5px"
            size="10px"
            type="success"
            v-show="goodsForm.category"
            >{{ goodsForm.category }}</el-tag
          >
        </el-form-item>
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="goodsForm.title"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="goodsForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="num">
          <el-input v-model="goodsForm.num"></el-input>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-col :span="11">
            <el-form-item prop="date1">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="goodsForm.date1"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2" style="text-align: center">-</el-col>
          <el-col :span="11">
            <el-form-item prop="date2">
              <el-time-picker
                placeholder="选择时间"
                v-model="goodsForm.date2"
                style="width: 100%"
              ></el-time-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="商品卖点" prop="sellPoint">
          <el-input v-model="goodsForm.sellPoint"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <el-button size="mini" type="primary" @click="uploadVisible = true"
            >上传图片</el-button
          >
          <!-- 上传图片展示 -->
          <div class="demo-image__preview" v-show="goodsForm.image">
            <el-image
              style="width: 100px; height: 100px"
              :src="goodsForm.image"
              :preview-src-list="srcList"
            >
            </el-image>
          </div>
        </el-form-item>
        <el-form-item label="商品描述" prop="descs">
          <!-- 富文本编辑器 -->
          <Editor @sendText="getText" ref="edit" />
        </el-form-item>
        <el-form-item label="规格参数" prop="descs" v-show="isShowParams">
          <el-form label-width="100px" class="demo-dynamic">
            <el-form-item
              v-for="(item, index) in paramsInfo"
              :label="item.value"
              :key="index"
              :prop="item.value"
            >
              <div class="content-item">
                <el-input v-model="item.value"></el-input>
              </div>

              <!-- 内层子表单 -->
              <el-form-item
                v-for="(item2, index2) in item.children"
                :label="item2.childValue"
                :key="index2"
                :prop="item2.childValue"
              >
                <div class="content-item child">
                  <el-input v-model="item2.childValue"></el-input>
                </div>
              </el-form-item>
            </el-form-item>
          </el-form>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="resetForm('goodsForm')">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('goodsForm')"
          >确 定</el-button
        >
      </span>

      <!-- 第一个内层嵌套弹窗---类目选择 -->
      <el-dialog
        width="40%"
        title="类目选择"
        :visible.sync="innerVisible"
        append-to-body
      >
        <Tree @sendTreeData="getTreeData" />
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="innerVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="showTreeData"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 第二个内层嵌套弹窗---上传图片 -->
      <!-- 内层嵌套弹窗---类目选择 -->
      <el-dialog
        width="40%"
        title="上传图片"
        :visible.sync="uploadVisible"
        append-to-body
      >
        <Upload @sendImgUrl="getImgUrl" />
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="uploadVisible = false"
            >取 消</el-button
          >
          <el-button size="mini" type="primary" @click="showImgUrl"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import Tree from "@/components/Tree";
import Upload from "@/components/Upload";
import Editor from "@/components/Editor";
import { addGoods, updateGoods, getCategoryData } from "@/api";
export default {
  components: {
    Tree,
    Upload,
    Editor,
  },
  props: ["title", "rowData"],
  data() {
    return {
      dialogVisible: false, // 外层弹窗
      innerVisible: false, // 内层弹窗(类目选择)
      uploadVisible: false, // 内层(图片上传)
      treeData: {},
      imgUrl: "", // 上传图片路径
      srcList: [],
      isShowParams: false,
      paramsInfo: [],
      goodsForm: {
        id: "",
        cid: "",
        category: "",
        title: "",
        price: "",
        num: "",
        date1: "",
        date2: "",
        sellPoint: "",
        image: "",
        descs: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        num: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
      },
    };
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.goodsForm = {
            category: "",
            title: "",
            price: "",
            num: "",
            date1: "",
            date2: "",
            sellPoint: "",
            image: "",
            descs: "",
          };
          this.$refs.edit.editor.txt.clear();
          done();
        })
        .catch((_) => {});
    },
    // 提交表单
    submitForm() {
      this.$refs.goodsForm.validate(async (valid) => {
        if (valid) {
          // 对象合并  paramsInfo是对象
          Object.assign(this.goodsForm, {
            paramsInfo: JSON.stringify(this.paramsInfo),
          });
          // 添加商品
          if (this.title === "添加商品") {
            let res = await addGoods(this.goodsForm);
            // 提交成功
            if (res.status === 200) {
              this.dialogVisible = false;
              this.$parent.goodsListData(1);
              // 清空表单
              this.goodsForm = {
                category: "",
                title: "",
                price: "",
                num: "",
                date1: "",
                date2: "",
                sellPoint: "",
                image: "",
                descs: "",
              };
              // 清空富文本框
              this.$refs.edit.editor.txt.clear();
              this.$message({
                type: "success",
                message: "添加成功",
              });
              // 清空规格参数
              this.paramsInfo = [];
              this.isShowParams = false;
            } else {
              // 提交失败
              this.$message({
                type: "error",
                message: "添加失败",
              });
            }
          } else {
            // 编辑商品
            let res = await updateGoods(this.goodsForm);
            if (res.status === 200) {
              this.dialogVisible = false;
              this.$parent.goodsListData(1);
              this.resetForm();
              this.$message({
                type: "success",
                message: "修改商品成功",
              });
            } else {
              this.$message({
                type: "error",
                message: "修改商品失败",
              });
            }
          }
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm() {
      this.$refs.goodsForm.resetFields();
      this.dialogVisible = false;
      this.$refs.edit.editor.txt.clear();
      this.paramsInfo = [];
      this.isShowParams = false;
      this.$message("已取消");
    },
    getTreeData(data) {
      this.treeData = data;
    },
    async showTreeData() {
      this.innerVisible = false;
      this.goodsForm.category = this.treeData.name;
      // 显示规格参数，发请求
      this.isShowParams = true;
      let obj = {
        cid: this.treeData.cid,
      };
      let res = await getCategoryData(obj);
      if (res.status === 200) {
        this.isShowParams = true;
        let info = res.result[0];
        this.paramsInfo = JSON.parse(info.paramData);
      } else {
        this.isShowParams = false;
      }
    },
    getImgUrl(url) {
      this.imgUrl = url;
    },
    showImgUrl() {
      this.goodsForm.image = this.imgUrl;
      this.uploadVisible = false;
      this.srcList.push(this.imgUrl);
    },
    // 获取富文本编辑器的内容
    getText(text) {
      this.goodsForm.descs = text.replace(/<[^>]+>/g, "");
    },
  },
  watch: {
    rowData(val) {
      this.goodsForm = this.rowData;
      // 给富文本框赋值
      // 这里需要注意的是：watch、computed、data、methods 是在挂载之前，所以在watch中获取不到dom元素，这里需要用到$nextTick
      this.$nextTick(() => {
        this.$refs.edit.editor.txt.html(val.descs);
        if (val.paramsInfo) {
          this.isShowParams = true;
          this.paramsInfo = JSON.parse(val.paramsInfo);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.demo-image__preview {
  margin-top: 10px;
}

.child {
  margin: 10px 0;
}
</style>
